package com.pucheng.bracelet.viewmodel.sao2

import androidx.lifecycle.*
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.clj.fastble.exception.BleException
import com.pucheng.bracelet.R
import com.pucheng.bracelet.app.ble.BleCmd
import com.pucheng.bracelet.app.ble.BleWriteAndNotifyCallback
import com.pucheng.bracelet.app.ble.ClientManager
import com.pucheng.bracelet.app.database.repository.Sao2Repository
import com.pucheng.bracelet.app.util.ByteUtils
import com.pucheng.bracelet.app.util.CacheUtil
import com.pucheng.bracelet.app.util.DatetimeUtil
import com.pucheng.bracelet.data.bean.Sao2Bean
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import java.text.DateFormat

class Sao2ViewModel(private val repository: Sao2Repository) : BaseViewModel() {
    val sao2 = MutableLiveData<Sao2Bean>().apply { value = CacheUtil.getSao2Info() }
    val allSao2To7Day: LiveData<List<Sao2Bean>> = repository.allSao2To7Day.asLiveData()
    val allSao2: LiveData<List<Sao2Bean>> = repository.allSao2.asLiveData()
    var measureState = MutableLiveData<Boolean>().apply { value = false }
    fun measuredSao2() {
        if (measureState.value!!) {
            //停止测量
            ToastUtils.showLong(R.string.stop_measuring)
            stopMeasured()
            return
        }
        measureState.value = true
        ToastUtils.showLong(R.string.start_measuring)
        ClientManager.getInstance()
            .sendControlCmd(BleCmd.MEASURED_BLOOD_OXYGEN, object : BleWriteAndNotifyCallback() {
                override fun onCharacteristicChanged(data: ByteArray?) {
                    if (data!![0] == ByteUtils.intToByte(0xFB) && data!![1] == ByteUtils.intToByte(
                            0x12
                        ) && data!![6] == ByteUtils.intToByte(0x04)
                    ) {
                        val time: Long =
                            ByteUtils.byteArrToInt(ByteUtils.subBytes(data, 2, 4)).toLong()
                        val sao2Bean = Sao2Bean(
                            0, data!![7].toInt(), TimeUtils.millis2String(
                                time,
                                DatetimeUtil.DATE_PATTERN_EE
                            )
                        )
                        sao2.value = sao2Bean
                        insert(sao2Bean)
                        CacheUtil.setSao2Info(sao2Bean)
                        measureState.value = false
                    }
                }

                override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                }

                override fun onWriteFailure(exception: BleException?) {
                    ToastUtils.showShort("测量失败")
                    measureState.value = false
                }
            })
    }

    private fun stopMeasured() {
        ClientManager.getInstance()
            .sendControlCmd(BleCmd.STOP_MEASURED, object : BleWriteAndNotifyCallback() {
                override fun onCharacteristicChanged(data: ByteArray?) {
//                    if (data!![0] == ByteUtils.intToByte(0xFB) && data!![1] == ByteUtils.intToByte(0x12) && data!![6] == ByteUtils.intToByte(0x03)){
//                        val time :Long= ByteUtils.byteArrToInt(ByteUtils.subBytes(data,2,4)).toLong()
//                        val bloodPressureBean = BloodPressureBean(0,data!![7].toInt(),data!![8].toInt(), TimeUtils.millis2String(time,"yyyy-MM-dd HH:mm:ss"))
//                        bpInfo.value = bloodPressureBean
//                        insert(bloodPressureBean)
//                        CacheUtil.setBloodPressureInfo(bloodPressureBean)
//                    }
//                    measureState.value = false
                }

                override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                    measureState.value = false
                }

                override fun onWriteFailure(exception: BleException?) {
                }
            })
    }

    fun insert(sao2Bean: Sao2Bean) = viewModelScope.launch {

        repository.insert(sao2Bean)
    }

//    fun getSao2List() = viewModelScope.launch {
//        repository.allSao2s()
//    }
}

class WordViewModelFactory(private val repository: Sao2Repository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(Sao2ViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return Sao2ViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}